package services

import (
	"bufio"
	"bytes"
	"dict-server/config"
	"dict-server/models/dto"
	parser "dict-server/utils"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

// DeepseekClient 实现ExampleService接口
type DeepseekClient struct {
	apiURL string       // API地址
	apiKey string       // 认证密钥
	client *http.Client // HTTP客户端
}

// NewDeepseekClient 创建Deepseek客户端实例（实现接口的构造函数）
func NewDeepseekClient(cfg *config.DeepseekConfig) ExampleService {
	return &DeepseekClient{
		apiURL: cfg.APIURL,
		apiKey: cfg.APIKey,
		client: &http.Client{Timeout: cfg.Timeout},
	}
}

// GetExamples 实现ExampleService接口的GetExamples方法
func (c *DeepseekClient) GetExamples(word string, examplesChan chan<- dto.Example, errorChan chan<- error) {
	defer close(examplesChan)
	defer close(errorChan)

	// 构建提示词
	prompt := fmt.Sprintf("请为单词'%s'提供5个中英文对照的例句。每个例句格式应为: 英文句子||中文翻译。不要有额外说明。", word)

	// 构建请求体-开启流式响应
	body := RequestBody{
		Model: "deepseek-chat",
		Messages: []Message{{
			Role:    "user",
			Content: prompt,
		}},
		Stream: true, // 开启流式响应
	}

	// 序列化请求体
	jsonBody, err := json.Marshal(body)
	if err != nil {
		errorChan <- fmt.Errorf("请求体序列化失败: %v", err)
		return
	}

	// 创建POST请求
	req, err := http.NewRequest("POST", c.apiURL, bytes.NewBuffer(jsonBody))
	if err != nil {
		errorChan <- fmt.Errorf("创建请求失败: %v", err)
		return
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+c.apiKey)

	// 发送请求
	resp, err := c.client.Do(req)
	if err != nil {
		errorChan <- fmt.Errorf("发送请求失败: %v", err)
		return
	}
	defer resp.Body.Close()

	// 检查响应状态
	if resp.StatusCode != http.StatusOK {
		errorChan <- fmt.Errorf("API返回非200状态: %d", resp.StatusCode)
		return
	}

	// 处理流式响应
	scanner := NewLineScanner(resp.Body)
	var fullResponse string

	// 逐行读取流式数据
	for scanner.Scan() {
		line := scanner.Text()
		if line == "" {
			continue
		}

		// 处理SSE格式（提取data字段内容）
		if len(line) > 6 && line[:6] == "data: " {
			line = line[6:]
		}
		if line == "[DONE]" { // 结束标志
			break
		}

		// 解析流式响应片段
		var streamResp StreamResponse
		if err := json.Unmarshal([]byte(line), &streamResp); err != nil {
			continue
		}
		// 累积生成的内容
		for _, choice := range streamResp.Choices {
			if choice.Delta.Content != "" {
				fullResponse += choice.Delta.Content
			}
		}
	}

	if err := scanner.Err(); err != nil {
		errorChan <- fmt.Errorf("读取响应失败: %v", err)
		return
	}

	// 解析例句并返回DTO
	examples, err := parser.ParseExamples(fullResponse)
	if err != nil {
		errorChan <- fmt.Errorf("解析例句失败: %v", err)
		return
	}

	// 模拟流式输出
	for _, example := range examples {
		examplesChan <- example
		time.Sleep(200 * time.Millisecond)
	}
}

// 以下为内部辅助结构和方法（保持不变）
type RequestBody struct {
	Model    string    `json:"model"`
	Messages []Message `json:"messages"`
	Stream   bool      `json:"stream"`
}

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type StreamResponse struct {
	ID      string   `json:"id"`
	Object  string   `json:"object"`
	Created int64    `json:"created"`
	Model   string   `json:"model"`
	Choices []Choice `json:"choices"`
}

type Choice struct {
	Index        int     `json:"index"`
	Delta        Delta   `json:"delta"`
	FinishReason *string `json:"finish_reason"`
}

type Delta struct {
	Content string `json:"content"`
}

type LineScanner struct {
	scanner *bufio.Scanner
}

func NewLineScanner(r io.Reader) *LineScanner {
	scanner := bufio.NewScanner(r)
	scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		for i := 0; i < len(data); i++ {
			if data[i] == '\n' {
				return i + 1, data[:i], nil
			}
		}
		if atEOF {
			return len(data), data, nil
		}
		return 0, nil, nil
	})
	return &LineScanner{scanner: scanner}
}

func (s *LineScanner) Scan() bool   { return s.scanner.Scan() }
func (s *LineScanner) Text() string { return s.scanner.Text() }
func (s *LineScanner) Err() error   { return s.scanner.Err() }
